package de.fhkl.gatav.ut.camera4atouchthreadcamview;

import java.io.IOException;

import android.content.Context;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.util.AttributeSet;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;


class CamSurfaceHolder extends SurfaceView implements SurfaceHolder.Callback{

	private SurfaceHolder surfaceHolder;
	private Camera		  cam;
	
	public CamSurfaceHolder(Context context, AttributeSet attrs){
		super(context,attrs);
		surfaceHolder = getHolder();
		surfaceHolder.addCallback(this);
		surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
	    //The Surface has been created, acquire the camera  
	    // if not already aquired and tell it where to draw.
		reOpenCam();
	    try {
	    	cam.setPreviewDisplay(holder);
	    } catch (IOException exception) {
	    	cam.release();
	    	cam = null;
	        // TODO: add more exception handling logic here
	    }
	    Log.d("CamSurfaceHolder","surfaceCreated");
	}
	
	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
		// Now that the size is known, set up the camera parameters and begin
		// the preview.
		Log.d("CamSurfaceHolder","surfaceChanged");
		if (cam!=null) {
			Camera.Parameters parameters = cam.getParameters();
			parameters.setPreviewSize(width, height);
			parameters.setPictureFormat(PixelFormat.JPEG);
			cam.setParameters(parameters);
			cam.startPreview();
		}
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
	    // Surface will be destroyed when we return, so stop the preview.
	    // Because the CameraDevice object is not a shared resource, it's very
	    // important to release it when the activity is paused.
		releaseCam();
		Log.d("CamSurfaceHolder","surfaceDestroyed");
	}

	public boolean startPrev(){
		if (cam!=null){
			cam.startPreview();
			return true;
		}else{
			return false;
		}
	}
	
	public boolean stopPrev(){
		if (cam!=null){
			cam.stopPreview();
			return true;
		}else{
			return false;
		}
	}
	
	public void releaseCam(){
		if (cam!=null){
			cam.stopPreview();
			cam.release();
			cam = null;			
		}
	}
	
	public void reOpenCam(){
		if (cam==null){
			cam = Camera.open();
		}
	}
}